#include "PD3DMesh.h"


PD3DMesh::PD3DMesh(LPDIRECT3DDEVICE9 device, char *str)
{
	LPD3DXBUFFER buffer;

	if (FAILED(D3DXLoadMeshFromXA(str, D3DXMESH_SYSTEMMEM,
		device, NULL, &buffer, NULL, &numMaterials, &mesh)))
	{
		throw new string("PD3DMesh::InitMesh()");
	}

	LPD3DXMATERIAL bufferMaterials = (LPD3DXMATERIAL)
		buffer->GetBufferPointer();
	materials = new D3DMATERIAL9[numMaterials];
	textures = new LPDIRECT3DTEXTURE9[numMaterials];

	for (DWORD i = 0; i < numMaterials; i++)
	{
		// copiando o material
		materials[i] = bufferMaterials[i].MatD3D;

		// definir aa cor ambiente para o material
		materials[i].Ambient = materials[i].Diffuse;

		textures[i] = NULL;
		if (bufferMaterials[i].pTextureFilename != NULL &&
			lstrlenA(bufferMaterials[i].pTextureFilename) > 0)
		{
			if (FAILED(D3DXCreateTextureFromFileA(device, 
				bufferMaterials[i].pTextureFilename,
				&textures[i])))
			{
				throw new string("PD3DMesh::InitMesh()::D3DXCreateTextureFromFileA");
			}
		}
	}

	buffer->Release();
	return ;
}

VOID PD3DMesh::Render(LPDIRECT3DDEVICE9 device)
{
	D3DXMATRIX matId;
		D3DXMatrixIdentity(&matId);
		device->SetTransform(D3DTS_WORLD, &matId);

	for(DWORD i = 0 ; i<numMaterials; i++)
		{
			device->SetMaterial(&materials[i]);
			device->SetTexture(0, textures[i]);
			mesh->DrawSubset(i);
		}
}

PD3DMesh::~PD3DMesh(void)
{
	mesh->Release();
}
